package com.bdtop.dbl.ui.activities.main;

import java.security.PublicKey;

import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult.AddressComponent;
import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.bluetooth.BleDeviceSettingsActivity;
import com.bdtop.dbl.bluetooth.BluetoothLeService;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.AddressResponse;
import com.bdtop.dbl.server.response.AllDeviceInfoResponse;
import com.bdtop.dbl.server.response.GetVersionResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.ui.activities.device.DeviceAddTipActivity;
import com.bdtop.dbl.ui.activities.device.DeviceTrackActivity;
import com.bdtop.dbl.ui.activities.device.FenceListActivity;
import com.bdtop.dbl.ui.activities.fragments.BesideFragment;
import com.bdtop.dbl.ui.activities.fragments.DeviceFragment;
import com.bdtop.dbl.ui.activities.fragments.LocationFragment;
import com.bdtop.dbl.ui.activities.fragments.MineFragment;
import com.bdtop.dbl.ui.activities.me.MsgActivity;
import com.bdtop.dbl.ui.view.ConfirmDialog;
import com.bdtop.dbl.ui.view.TitleBar;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.DBLDebug;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;
import com.bdtop.dbl.utils.UpdateService;
import com.igexin.sdk.PushManager;

/**
 * @ClassName: MainActivity
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-26
 */
public class MainActivity extends BaseActivity {

	private final static String btnIndex = "btnIndex";
	private final static String action = "action";

	public static final void launch(Context context) {
		DBLDebug.logd("launch main use default");
		Intent intent = new Intent(context, MainActivity.class);
		context.startActivity(intent);
	}

	/**
	 * <b>btnIndex</b><br>
	 * 表示当前页面，0 位置 1身边 2列表 3我
	 */
	int want;

	public static final int WHAT_DEFAULT = 0;
	public static final int WHAT_FROM_BLE_SERVICE = 1;
	public static final int WHAT_FROM_PUSH_SOS = 2;

	public static final long ACTION_BLE_RESEARCH = 99;
	public static long currAction = -1;
	public static final long ACTION_LOCATION = 98;

	public static final void launch(Context context, int index) {
		DBLDebug.logd("launch main use index" + index);
		Intent intent = new Intent(context, MainActivity.class);
		intent.putExtra(btnIndex, index);
		context.startActivity(intent);
	}

	public static final void launch(Context context, long mAction) {
		DBLDebug.logd("launch main use action" + mAction);
		Intent intent = new Intent(context, MainActivity.class);

		currAction = mAction;
		context.startActivity(intent);
	}

	public TitleBar mTitleBar;
	private RadioGroup mTabGroup;
	private RadioButton mLocationTab, mBesideTab, mMeTab, mDeviceTab;

	private FragmentManager mFragmentManager;
	private LocationFragment mLocationFragment;
	private BesideFragment mBesideFragment;
	private MineFragment mMineFragment;
	private DeviceFragment mDeviceFragment;
	private PackageInfo info = null;

	// menu
	public ImageButton btnTrack;
	public Button btnDeviceAdd;
	public Button btnBleSet;

	public Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1111:
				versionUpdate();
				break;
			}
		};
	};

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_main);
		super.onCreate(savedInstanceState);
		mSearch = GeoCoder.newInstance();

		PushManager.getInstance().initialize(this.getApplicationContext());

		mFragmentManager = getFragmentManager();
		mLocationFragment = new LocationFragment();
		mMineFragment = new MineFragment();
		mDeviceFragment = new DeviceFragment();
		mBesideFragment = new BesideFragment();

		FragmentTransaction transaction = mFragmentManager.beginTransaction();
		transaction.add(R.id.content, mLocationFragment);
		transaction.add(R.id.content, mMineFragment);
		transaction.add(R.id.content, mDeviceFragment);
		transaction.add(R.id.content, mBesideFragment);

		transaction.commit();

		initViews();

		want = getIntent().getIntExtra(btnIndex, 0);
		DBLDebug.logd("main want selected menu item is" + want);
		if (want == 0) {
			mLocationTab.setChecked(true);
		} else if (want == 3) {
			mMeTab.setChecked(true);
		} else if (want == 1) {
			mBesideTab.setChecked(true);
			DBLDebug.logd("open beside fragment as default");
		}

		mHandler.sendEmptyMessageDelayed(1111, 1000);

		popFlag = findViewById(R.id.pop_flag);

		// 游客？
		// isVisitorMode();
		// 测试账号登录，只显示一次 游客模式提示. 测试账号000000[不触发isLogin为ture]
		boolean isVisitorMode = !Preferences.isLogin(MainActivity.this);
		if (isVisitorMode) {
			ConfirmDialog c = new ConfirmDialog(this, getString(R.string.hint_tourists), false, null);
			c.show(false);
		}

		/** 注册新账户后首次登录直接进入设备添加页面（只有第一次是这样） */
		boolean toAddDevice = Preferences.getRegisterToLogin(getApplicationContext());
		if (toAddDevice) {
			DeviceAddTipActivity.launch(MainActivity.this);
		}
		Preferences.saveRegisterToLogin(getApplicationContext(), false);
	}

	private void versionUpdate() {
		try {
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
		}
		ServerApiFactory.getApiImpl().getVersion(callback);
	}

	private void showUpdateDialog() {
		final Dialog dialog = new Dialog(this, R.style.Theme_Light_NoTitle_Dialog);
		View content = LayoutInflater.from(this).inflate(R.layout.dialog_confirm_2, null);

		TextView txMessage = (TextView) content.findViewById(R.id.tx_message);
		txMessage.setText(R.string.update_msg);

		OnClickListener listener = new OnClickListener() {
			@Override public void onClick(View arg0) {
				dialog.dismiss();

				if (arg0.getId() == R.id.btn_confirm) {
					Intent intent = new Intent(MainActivity.this, UpdateService.class);
					intent.putExtra("Key_App_Name", getString(R.string.app_name));
					intent.putExtra("Key_Down_Url", Preferences.getDownurl(MainActivity.this));
					startService(intent);
				}
			}
		};

		Button btnCon = (Button) content.findViewById(R.id.btn_confirm);
		btnCon.setOnClickListener(listener);
		btnCon.setText(R.string.just_update);
		Button btnCan = (Button) content.findViewById(R.id.btn_cancel);
		btnCan.setOnClickListener(listener);
		btnCan.setText(R.string.not_update);

		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(content);
		dialog.show();
	}

	RequestCallback callback = new RequestCallback() {

		@Override public void onSuccess(String rawData, Object response) {
			GetVersionResponse getVersionResponse = (GetVersionResponse) response;
			if (getVersionResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {
				// fix: 一次性commit
				Preferences.saveVersion(MainActivity.this, getVersionResponse.getVersion().toString());
				// Editor editor =
				// Preferences.getPreferences(MainActivity.this).edit();
				// editor.putString(Preferences.VERSION,
				// getVersionResponse.getVersion().toString());
				if (!TextUtils.isEmpty(getVersionResponse.getDownurl())) {
					Preferences.saveDownurl(MainActivity.this, getVersionResponse.getDownurl());
					// editor.putString(Preferences.DOWNURL,
					// getVersionResponse.getDownurl());
				}
				float ver = Float.valueOf(info.versionName);
				int version = (int) (ver * 100);
				if (getVersionResponse.getVersion() > version) {
					showUpdateDialog();
				}
				// editor.commit();
			}
		}

		@Override public void onError(int statusCode, Throwable e, String rawData) {

		}
	};

	public String rebindImei;

	@Override protected void onStop() {
		super.onStop();
		rebindImei = null;
	}

	@Override protected void onResume() {
		super.onResume();

		rebindImei = Preferences.getRebindImei(this);
		DBLDebug.logd("main onresume");
		if (!TextUtils.isEmpty(rebindImei)) {
			DBLDebug.logd("to deside rebind!! imei is " + rebindImei);
			mBesideTab.setChecked(true);
			Preferences.saveRebindImei(this, "");
		}

		if (currAction == ACTION_BLE_RESEARCH) {
			mBesideTab.setChecked(true);
			// 重新扫描绑定
			if (mBesideFragment != null) {
				mBesideFragment.disconnectBLE();
				mBesideFragment.requestScanBLE();
			}
		}
		//
		else if (currAction == ACTION_LOCATION) {
			mLocationTab.setChecked(true);
		}

		toAutoRereshList();
	}

	private final int MSG_REFRESH_LIST = 564;
	private Handler handler = new Handler() {
		@Override public void dispatchMessage(Message msg) {
			if (MSG_REFRESH_LIST == msg.what) {
				getAllDeviceInfo(true);
			}
		}
	};

	public void toAutoRereshList() {
		stopAutoRereshList();
		handler.sendEmptyMessageDelayed(MSG_REFRESH_LIST, 10 * 1000);
	}

	private void stopAutoRereshList() {
		handler.removeMessages(MSG_REFRESH_LIST);
	}

	@Override protected void onPause() {
		super.onPause();
		stopAutoRereshList();
	}

	/**
	 * 获取所有设备即时信息
	 * 
	 * @param auto
	 *            自动刷新 频率 10秒
	 */
	public void getAllDeviceInfo(final boolean auto) {
		if (DBLApplication.getInstance().currentDi == null && (!mLocationFragment.isHidden() || !mDeviceFragment.isHidden())) {
			// 初次获得
			if (want == 1 || want == 3) {
				// 身边和我模块显示的时候
			} else {
				// 位置和设备列表模块显示的时候
				setAndShowWaitingMessage(R.string.wating_get_device_list);
			}
		} else {
			// 再次手动获得
			if (!auto) {
				setAndShowWaitingMessage(R.string.wating_get_device_list_2);
			}
		}
		// 发出请求
		ServerApiFactory.getApiImpl().getAllDeviceInfo(loginSign, new RequestCallback() {
			@Override public void onSuccess(String rawData, Object response) {
				clearAndHiddenWaitingMessage();
				AllDeviceInfoResponse adir = (AllDeviceInfoResponse) response;
				String status = adir.getStatus();
				if (Constants.REQUEST_SUCCESS.equals(status)) {
					DBLApplication.getInstance().deviceInfoList = adir.device_info;

					/**
					 * fix : 初始点坐标 是0.0
					 */
					if (DBLApplication.getInstance().deviceInfoList != null) {
						String[] latlng = Preferences.getLastSelfLocation(MainActivity.this);
						for (DeviceInfo cd : DBLApplication.getInstance().deviceInfoList) {
							if (cd.pos.lat == 0.0 && cd.pos.lon == 0.0) {
								if(latlng != null){
									cd.pos.lat = Double.parseDouble(latlng[0]);
									cd.pos.lon = Double.parseDouble(latlng[1]);	
								}
							}
						}
					}

					/**
					 * fix: 重新设置currentDi引用,为最新list里对应imei的DeviceInfo
					 */
					if (DBLApplication.getInstance().deviceInfoList != null) {
						boolean find = false;
						for (DeviceInfo cd : DBLApplication.getInstance().deviceInfoList) {
							if (DBLApplication.getInstance().currentDi != null) {
								if (cd.imei.equals(DBLApplication.getInstance().currentDi.imei)) {
									DBLApplication.getInstance().currentDi = cd;
									find = true;
									break;
								}
							}
						}
						if (!find) {
							DBLApplication.getInstance().currentDi = DBLApplication.getInstance().deviceInfoList.get(0);
						}
					}

					initDeviceList();

					
					try {
						if (DBLApplication.getInstance().firstFlag_LoginButNoDevice
								&& (DBLApplication.getInstance().deviceInfoList == null || DBLApplication.getInstance().deviceInfoList.size() < 1)) {
							// 登录后 没有设备绑定 ， 显示 设备页面 [仅一次]
							DBLApplication.getInstance().firstFlag_LoginButNoDevice = false;
							mDeviceTab.performClick();
						}
					} catch (Exception e) {
						DBLDebug.loge("getAllDeviceInfo onSuccess() mDeviceTab.performClick\n"+ e.getMessage());
					}

					// 自动刷新
					if (auto && DBLApplication.getInstance().deviceInfoList != null) {
						toAutoRereshList();
					}
				} else {
					if (DBLApplication.getInstance().deviceInfoList != null) {
						DBLApplication.getInstance().deviceInfoList.clear();
						DBLApplication.getInstance().currentDi = null;
					}
				}
			}

			@Override public void onError(int statusCode, Throwable e, String rawData) {
				clearAndHiddenWaitingMessage();
				showToast(NetworkUtils.isNetConnect(MainActivity.this) ? R.string.oper_error : R.string.net_error);

				// 自动刷新
				if (auto) {
					toAutoRereshList();
				}
			}
		});
	}

	public void initDeviceList() {
		if (mDeviceFragment != null) {
			mLocationFragment.init();
		}
		if (mDeviceFragment != null) {
			mDeviceFragment.init();
		}
	}

	public static final int ADD_DEVICE_FROM_MAIN = 1;

	@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == ADD_DEVICE_FROM_MAIN) {
				mBesideTab.setChecked(true);
				getAllDeviceInfo(false);
			}
		}
	}

	public void setTabTitle(String title) {
		mTitleBar.setTitle(title);
	}

	public void setTabTitle(int resId) {
		mTitleBar.setTitle(resId);
	}

	private void initViews() {
		mTitleBar = (TitleBar) findViewById(R.id.title_bar);
		mTitleBar.setBelongActivity(this);
		mTitleBar.setBackShowOrHidden(View.GONE);
		initMenus();

		mTabGroup = (RadioGroup) findViewById(R.id.rg_tab);
		mTabGroup.setOnCheckedChangeListener(mOnCheckedChangeListener);
		mTabGroup.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_in_bottom));
		mLocationTab = (RadioButton) findViewById(R.id.tab_lacation);
		mBesideTab = (RadioButton) findViewById(R.id.tab_beside);
		mDeviceTab = (RadioButton) findViewById(R.id.tab_device);

		mMeTab = (RadioButton) findViewById(R.id.tab_me);
	}

	/**
	 * 加载标题栏的右侧按钮
	 */
	private void initMenus() {
		// 位置界面的轨迹按钮
		btnTrack = new ImageButton(MainActivity.this);
		btnTrack.setBackgroundResource(R.drawable.selector_title_blue_btn_bg);
		btnTrack.setImageResource(R.drawable.clock232);
		btnTrack.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		btnTrack.setVisibility(View.GONE);
		btnTrack.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View arg0) {
				DeviceTrackActivity.launch(MainActivity.this);
			}
		});
		mTitleBar.addMenu(btnTrack);
		// 身边界面的设置按钮
		btnBleSet = new Button(MainActivity.this);
		btnBleSet.setText(R.string.settings_title);
		btnBleSet.setBackgroundResource(R.drawable.selector_title_blue_btn_bg);
		btnBleSet.setTextColor(Color.WHITE);
		btnBleSet.setVisibility(View.GONE);
		btnBleSet.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View arg0) {
				String mac = mBesideFragment.getConnectedBluetoothDeviceAddress();
				BleDeviceSettingsActivity.launch(MainActivity.this, mac);
			}
		});
		mTitleBar.addMenu(btnBleSet);
		// 列表界面的添加按钮
		btnDeviceAdd = new Button(MainActivity.this);
		btnDeviceAdd.setText(R.string.add);
		btnDeviceAdd.setBackgroundResource(R.drawable.selector_title_blue_btn_bg);
		btnDeviceAdd.setTextColor(Color.WHITE);
		btnDeviceAdd.setVisibility(View.GONE);
		btnDeviceAdd.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View arg0) {
				DeviceAddTipActivity.launch(MainActivity.this);
			}
		});
		mTitleBar.addMenu(btnDeviceAdd);
	}

	/**
	 * 下部菜单切换
	 */
	private OnCheckedChangeListener mOnCheckedChangeListener = new OnCheckedChangeListener() {

		@Override public void onCheckedChanged(RadioGroup group, int checkedId) {
			FragmentTransaction transaction = mFragmentManager.beginTransaction();
			transaction.hide(mLocationFragment);
			transaction.hide(mMineFragment);
			transaction.hide(mDeviceFragment);
			transaction.hide(mBesideFragment);

			btnDeviceAdd.setVisibility(View.GONE);
			btnTrack.setVisibility(View.GONE);
			btnBleSet.setVisibility(View.GONE);

			switch (checkedId) {
			case R.id.tab_lacation:
				want = 0;
				mTitleBar.setTitle(R.string.tab_location);
				transaction.show(mLocationFragment);
				if (DBLApplication.getInstance().deviceInfoList != null && DBLApplication.getInstance().deviceInfoList.size() > 0) {
					// 有设备显示轨迹按钮
					btnTrack.setVisibility(View.VISIBLE);
				}
				getAllDeviceInfo(true);
				break;
			case R.id.tab_beside:
				want = 1;
				mTitleBar.setTitle(R.string.tab_beside);
				transaction.show(mBesideFragment);
				if (mBesideFragment.isConnected()) {
					// 已连接显示设置按钮
					btnBleSet.setVisibility(View.VISIBLE);
					
					
				}
				mBesideFragment.toShowFirstRemindInfo(); //
				
				break;
			case R.id.tab_device:
				want = 2;
				transaction.show(mDeviceFragment);
				mTitleBar.setTitle(R.string.device_list_title);
				btnDeviceAdd.setVisibility(View.VISIBLE);
				break;
			case R.id.tab_me:
				want = 3;
				transaction.show(mMineFragment);
				mTitleBar.setTitle(R.string.info_title);
				break;
			}
			transaction.commitAllowingStateLoss();
		}
	};

	private long exitTime = 0;

	/**
	 * 双击退出
	 */
	@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), R.string.exit_app_tip, Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
//				if (BesideFragment.isScanOver) {
//					releaseGatt();
					DBLApplication.getInstance().exit();
//				}
//				} else {
//					showWaitingDialog("退出中，请稍候", true, true);
//					new Handler().postDelayed(runExit, 5000);
//				}
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	

	public void releaseGatt() {
		if (mBesideFragment != null) { // 退出检测。 是否 主动断开蓝牙连接。 ?
			// 主动断开连接，就关闭服务。
			BluetoothLeService mBluetoothLeService = mBesideFragment.getBluetoothLeService();
			if (mBluetoothLeService != null) {
				mBluetoothLeService.releaseGatt();
			}
		}
	}

	/** ****************设备信息遮罩层，用于位置模块***************** */
	private View popFlag;
	private PopupWindow mPopDeviceInfo;
	private TextView txLocation;
	private String popShowDeviceMdn;

	public void showDeviceInfoPop() {
		DeviceInfo popShowDevice = DBLApplication.getInstance().currentDi;
		if (popShowDevice == null) {
			return;
		}
		popShowDeviceMdn = popShowDevice.mdn;
		View content = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_device_info, null);
		((TextView) content.findViewById(R.id.tx_device_name)).setText(popShowDevice.name);

		// 2015 new api
		txLocation = (TextView) content.findViewById(R.id.tx_location);
//		String addressName = null ; 
//		if(DBLApplication.getInstance().deviceInfoList != null){
//			for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
//				if(popShowDevice.mdn.equals(di.mdn)){
//					if(di.pos != null && di.pos.addrname != null && !"null".equals(di.pos.addrname )){
//						addressName = di.pos.addrname ;
//						break;
//					}
//				}
//			}
//		}
//		
//		String addressName = DBLApplication.getInstance().getAddressInfoByMdn(popShowDeviceMdn);
//		
//		if(TextUtils.isEmpty(addressName)){
//			addressName = DBLApplication.getInstance().getAddressInfoByMdn(popShowDevice.mdn);
//			if (TextUtils.isEmpty(addressName)) {
//				txLocation.setText(Constants.EMPTY_ADDRESS_INFO);
//				if (popShowDevice.pos != null) {
//					requestDeviceAddressInfo(txLocation , popShowDevice.pos.lon, popShowDevice.pos.lat
//							, popShowDeviceMdn);
//				}
//			} else {
//				txLocation.setText(addressName);
//			}
//		} else {
//			txLocation.setText(addressName);
//		}
		
		
		if (popShowDevice.pos != null) {
			txLocation.setText(Constants.EMPTY_ADDRESS_INFO);
			requestDeviceAddressInfo(txLocation , popShowDevice.pos.lon, popShowDevice.pos.lat
					, popShowDeviceMdn);
		} else {
			txLocation.setText(Constants.ERROR_ADDRESS_INFO);
		}
		
		
		((TextView) content.findViewById(R.id.tx_time)).setText(DBLApplication.getInstance().currentDi.pos.time);

		/* 用power判断 */
		// String power = DBLApplication.getInstance().currentDi.power;
		// int deviceState = power.equals("on") ? 1 : 2;
		// String[] dState =
		// getResources().getStringArray(R.array.device_state);
		// if (deviceState > dState.length || deviceState < 1)
		// deviceState = 1;
		// ((TextView)
		// content.findViewById(R.id.tx_device_state)).setText(dState[deviceState
		// - 1]);

		int currentMode = DBLApplication.getInstance().currentDi.location_mode;
		String[] lMode = getResources().getStringArray(R.array.device_location_mode);
		if (currentMode > lMode.length || currentMode < 1)
			currentMode = 1;
		((TextView) content.findViewById(R.id.tx_mode)).setText(lMode[currentMode - 1]);

		ImageView imgElec = (ImageView) content.findViewById(R.id.img_device_elec);
		imgElec.setImageResource(R.drawable.icon_elec);

		TextView txElec = (TextView) content.findViewById(R.id.tx_device_elec);
		if (DBLApplication.getInstance().currentDi.elec > 100 || DBLApplication.getInstance().currentDi.elec < 0) {
			imgElec.setImageResource(R.drawable.elec_online3);
			txElec.setText(getString(R.string.unkown));
		} else if (DBLApplication.getInstance().currentDi.elec >= 80) {
			imgElec.setImageResource(R.drawable.elec_online3);
			txElec.setText(DBLApplication.getInstance().currentDi.elec + "%");
		} else if (DBLApplication.getInstance().currentDi.elec > 20) {
			imgElec.setImageResource(R.drawable.elec_online2);
			txElec.setText(DBLApplication.getInstance().currentDi.elec + "%");
		} else {
			imgElec.setImageResource(R.drawable.elec_online);
			txElec.setText(DBLApplication.getInstance().currentDi.elec + "%");
		}

		int deviceAV = DBLApplication.getInstance().currentDi.av;
		String[] dav = getResources().getStringArray(R.array.device_av);
		if (deviceAV > dav.length || deviceAV < 1)
			deviceAV = 1;
		((TextView) content.findViewById(R.id.tx_av)).setText(dav[deviceAV - 1]);

		OnClickListener popDeviceOperListner = new OnClickListener() {
			@Override public void onClick(View view) {
				switch (view.getId()) {
				case R.id.layout_device_message:
					MsgActivity.launch(MainActivity.this, DBLApplication.getInstance().currentDi.mdn);
					break;
				case R.id.layout_device_track:
					DeviceTrackActivity.launch(MainActivity.this);
					break;
				case R.id.layout_device_fence:
					FenceListActivity.launch(MainActivity.this, DBLApplication.getInstance().currentDi.mdn);
					break;
				}

				if (mPopDeviceInfo != null && mPopDeviceInfo.isShowing()) {
					mPopDeviceInfo.dismiss();
					mPopDeviceInfo = null;
				}
			}
		};

		content.findViewById(R.id.layout_device_message).setOnClickListener(popDeviceOperListner);
		content.findViewById(R.id.layout_device_track).setOnClickListener(popDeviceOperListner);
		content.findViewById(R.id.layout_device_fence).setOnClickListener(popDeviceOperListner);

		mPopDeviceInfo = new PopupWindow(content, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		mPopDeviceInfo.setBackgroundDrawable(new ColorDrawable(0));
		mPopDeviceInfo.setOutsideTouchable(true);
		mPopDeviceInfo.setFocusable(true);
		mPopDeviceInfo.setAnimationStyle(R.style.Animation_PopWindow_Main_ShowDeviceInfo);
		int[] locations = new int[2];
		popFlag.getLocationOnScreen(locations);
		mPopDeviceInfo.showAtLocation(popFlag, Gravity.NO_GRAVITY, locations[0], locations[1] + popFlag.getHeight());
	}

	GeoCoder mSearch = null;
	
	private void requestDeviceAddressInfo(final TextView txInfo, double lon, double lat,final String mdn) {
		LatLng ptCenter = new LatLng(lat, lon);
		mSearch.reverseGeoCode(new ReverseGeoCodeOption()
				.location(ptCenter));
		mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
			@Override public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
				if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
					Log.e("LocationFragmet", "onGetReverseGeoCodeResult 抱歉未能找到结果");
					
					return;
				}
				String info = result.getAddress();
				txInfo.setText(info);
				DBLDebug.logd("存储设备:[" + mdn + "]地址信息 ["+info+"]至Application中");
				DBLApplication.getInstance().setAddressInfoByMdn(mdn, info);
			}
				
			@Override public void onGetGeoCodeResult(GeoCodeResult result) {
				if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
					Log.e("LocationFragmet", "onGetGeoCodeResult 抱歉未能找到结果");
					return;
				}
				String strInfo = String.format("纬度：%f 经度：%f",
						result.getLocation().latitude, result.getLocation().longitude);
				Log.e("LocationFragmet", strInfo);
			}
		});
	}
	

	@Override protected void onDestroy() {
		super.onDestroy();
		handler.removeMessages(MSG_REFRESH_LIST);
		mHandler.removeMessages(1111);
		
		mSearch.destroy();
	}
	
	
}
